//
//  Simple request-reply broker
//

package main

import (
	"fmt"
	"os"
	"zmq"
)

func zmq_main() os.Error {
	context, err := zmq.Init(1)
	if err != nil {
		return err
	}
	defer context.Close()

	frontend, err := context.Socket(zmq.ROUTER)
	if err != nil {
		return err
	}
	defer frontend.Close()

	backend, err := context.Socket(zmq.DEALER)
	if err != nil {
		return err
	}
	defer backend.Close()

	err = frontend.Bind("tcp://*:5559")
	if err != nil {
		return err
	}
	err = backend.Bind("tcp://*:5560")
	if err != nil {
		return err
	}

	items := make([]zmq.PollItem, 2)
	items[0].SetSocket(frontend)
	items[0].SetEvents(zmq.POLLIN)
	items[1].SetSocket(backend)
	items[1].SetEvents(zmq.POLLIN)

	msg, err := zmq.InitMsg()
	if err != nil {
		return err
	}
	defer msg.Close()
	for {
		zmq.Poll(items, -1)
		if items[0].GetRevents()&zmq.POLLIN == zmq.POLLIN {
			for {
				_, err := frontend.RecvMsg(msg, 0)
				if err != nil {
					return err
				}
				more, err := frontend.GetOptionInt64(zmq.RCVMORE)
				if err != nil {
					return err
				}
				var flags zmq.TransFlag = 0
				if more > 0 {
					flags |= zmq.SNDMORE
				}
				err = backend.SendMsg(msg, flags)
				if err != nil {
					return err
				}
				if more == 0 {
					break
				}
			}
		}
		if items[1].GetRevents()&zmq.POLLIN == zmq.POLLIN {
			for {
				_, err := backend.RecvMsg(msg, 0)
				if err != nil {
					return err
				}
				more, err := backend.GetOptionInt64(zmq.RCVMORE)
				if err != nil {
					return err
				}
				var flags zmq.TransFlag = 0
				if more > 0 {
					flags |= zmq.SNDMORE
				}
				err = frontend.SendMsg(msg, flags)
				if more == 0 {
					break
				}
			}
		}
	}
	return nil
}

func main() {
	fmt.Println("Simple request-reply broker")
	err := zmq_main()
	if err != nil {
		fmt.Println(err)
	}
}
